package com.ccc3gc.mysystem.service.impl;

import com.ccc3gc.mysystem.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

@Service
public class FileServicedImpl implements FileService {
    private static final String UPLOAD_USER_DIR="D:\\mysystem\\RuoYi-Vue-master\\ruoyi-admin\\src\\main\\resources\\static\\ upload.";
    /**图片上传
     * @return
     */
    @Override
    public String uploadImage(MultipartFile uploadFile) {
        String originalFilename = uploadFile.getOriginalFilename();//获得文件名称及后缀
        String curDateStr = LocalDate.now().toString();
        File targetDir=new File(UPLOAD_USER_DIR,curDateStr);
        if(!targetDir.exists()){
            targetDir.mkdirs();
        }

        String extension = StringUtils.getFilenameExtension(originalFilename);
        String fileName = UUID.randomUUID().toString().replaceAll("-","");
        String targetFileName = fileName+"."+extension;

        try {
            uploadFile.transferTo(new File(targetDir,targetFileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //删除空白文件夹
        File oldFile =new File(UPLOAD_USER_DIR);
        File[] array = oldFile.listFiles();
        for (int i=0;i<array.length;i++) {
            File[] f2 = array[i].listFiles();
            if(!array[i].isFile()) {
                //if(f2==null) break;
                if (f2.length == 0) {
                    array[i].delete();
                }
            }
        }
        return "/upload/user/"+curDateStr+"/"+targetFileName;
    }
}
